package com.xinting.piano.app;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hannesdorfmann.swipeback.Position;
import com.hannesdorfmann.swipeback.SwipeBack;
import com.xinting.piano.R;
import com.xinting.piano.data.PApp;
import com.xinting.piano.data.PComment;
import com.xinting.piano.data.PError;
import com.xinting.piano.data.PMelody;
import com.xinting.piano.data.PUser;
import com.xinting.piano.lib.audio.PAudio;
import com.xinting.piano.lib.storage.PStorage;
import com.xinting.piano.lib.util.PUtil;
import com.xinting.piano.service.IHandleJson;
import com.xinting.piano.service.PAlbum;
import com.xinting.piano.service.PCommentService;
import com.xinting.piano.view.ICustomControlView;
import com.xinting.piano.view.PAlbumView;
import com.xinting.piano.view.PControlView;
import com.xinting.piano.view.PLikeControlView;
import com.xinting.piano.view.PUserControlView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by wuxinting on 15/10/29.
 * 播放乐曲活动
 */
public class PAlbumActivity extends PBaseActivity {

    private static int WHAT_UPDATE_PROGRESS_PLAY = 1;
    private static int WHAT_UPDATE_PROGRESS_DOWNLOAD = 2;
    private static int WHAT_LIKE = 3;

    private PMelody melody;
    private PAlbumView albumView;
    private PControlView playControlView;
    private PControlView commentControlView;
    private PControlView userControlView;
    private PControlView likeControlView;
    private ICustomControlView userCustomControl;
    private ICustomControlView likeCustomControl;

    private LinearLayout albumContainer;
    private ProgressBar progressBar;
    private TextView progressLabel;
    private TextView likeNum;
    private PAlbum album;

    private List<PComment> comments;
    private PCommentAdapter commentAdapter;
    private Handler handler;

    private IHandleJson handleJson;
    //定时刷新
    private ScheduledThreadPoolExecutor executor;
    private ScheduledFuture<?> refreshTask;

    /**
     * 本地已经存在的该乐曲的音频文件，或者将要存入（通过下载方式）音频数据的文件
     */
    private File albumFile;

    public static final String LOG_TAG = PApp.LOG_TAG+"_album";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SwipeBack.attach(this, Position.LEFT)
            .setContentView(R.layout.activity_album)
            .setSwipeBackView(R.layout.swipeback_default);

        //获得传入的参数
        Intent intent = getIntent();
        melody = (PMelody) intent.getSerializableExtra(PMelody.KEY);

        //UI更新handler
        handler = new AlbumHandle();
        executor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);

        //获取本地的音频文件
        try {
            albumFile = PStorage.getInstance().getFile(melody.getId()+PMelody.MELODY_SUFFIX);
        } catch (IOException e) {
            Log.e(LOG_TAG, e.getMessage());
        }
        //album业务对象
        album = new PAlbum(albumFile);
        album.setPlayComplete(new OnPlayCompleteListener());

        //更新头栏
        ActionBar bar = getSupportActionBar();
        if (bar != null) {
            bar.setTitle(R.string.app_album);
        }

        //设置各view
        albumView = $(R.id.album);
        playControlView = $(R.id.album_play);
        commentControlView = $(R.id.album_comment);
        userControlView = $(R.id.album_user);
        likeControlView = $(R.id.album_like);
        albumContainer = $(R.id.album_container);
        progressBar = $(R.id.album_progress);
        progressLabel = $(R.id.album_progress_label);
        likeNum = $(R.id.album_like_num);

        //调整album控件的size，在ScrollView中, 自适应的宽高不被正确计算，要拖动输入确定的宽高
        Display display = getWindowManager().getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);

        albumView.setAuthor(melody.getUser().getNick());
        albumView.setTitle(melody.getTitle());
        albumView.setMinimumWidth(metrics.widthPixels);
        albumView.setMinimumHeight(metrics.widthPixels);

        playControlView.setOnClickListener(new OnPlayListener());

        //设置为评论控件(暂时不提供评论功能)
        commentControlView.setVisibility(View.GONE);
//        commentControlView.addCustomControlView(new PCommentControlView());
//        commentControlView.setCustomType(PApp.CONTROL_VIEW_COMMENT);
//        commentControlView.setOnClickListener(new OnCommentListener());

        //设置为用户图标控件
        userCustomControl = new PUserControlView();
        userControlView.addCustomControlView(userCustomControl);
        userControlView.setCustomType(PApp.CONTROL_VIEW_USER);
        userControlView.setOnClickListener(new OnUserListener());

        //设置喜欢图标控件
        likeCustomControl = new PLikeControlView();
        likeControlView.addCustomControlView(likeCustomControl);
        likeControlView.setCustomType(PApp.CONTROL_VIEW_LIKE);
        likeControlView.setOnClickListener(new OnLikeListener());

        comments = new ArrayList<>();
        commentAdapter = new PCommentAdapter(this, comments);
        commentAdapter.setUserAdapter(new PUserAdapter(this));

        progressLabel.setText(melody.getDurationString());
        likeNum.setText(Long.toString(melody.getLike()) + $s(R.string.album_like_num));

        handleJson = new HandleResult();

//        PCommentService commentService = new PCommentService(melody);
//        commentService.getMelodyComments(3, handleJson);
    }

    @Override
    protected void onResume() {
        super.onResume();

        userControlView.addCustomControlView(userCustomControl);
        userControlView.setCustomType(PApp.CONTROL_VIEW_USER);

        likeControlView.addCustomControlView(likeCustomControl);
        likeControlView.setCustomType(PApp.CONTROL_VIEW_LIKE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        pause(null);
    }

    //play
    private boolean play(PControlView controlView) {
        if (album.getStatus() == PAlbum.Status.PAUSE) {
            album.resumePlay();

            albumView.startRoll();
            refreshTask = executor.scheduleAtFixedRate(new RefreshRunnable(), 0, 1, TimeUnit.SECONDS);
            controlView.setStatus(PControlView.Status.PAUSE);
            return true;
        }

        if (albumFile.length() <= 0) {
            album.downloadMelody(melody.getId(), handleJson);
        } else {
            //本地文件下载已经完成
            if (!album.play()) {
                albumFile.delete();
                play(controlView);
            }
            progressBar.setMax(PAudio.getInstance().getDuration());
            progressBar.setSecondaryProgress(progressBar.getMax());
        }

        albumView.startRoll();
        progressBar.setMax(PAudio.getInstance().getDuration());
        refreshTask = executor.scheduleAtFixedRate(new RefreshRunnable(), 0, 1, TimeUnit.SECONDS);
        controlView.setStatus(PControlView.Status.PAUSE);
        return true;
    }

    //pause
    private boolean pause(PControlView controlView) {
        album.pausePlay();

        albumView.stopRoll();
        if (refreshTask != null) {
            refreshTask.cancel(true);
        }

        if (controlView != null) {
            controlView.setStatus(PControlView.Status.PLAY);
        }
        return true;
    }

    /**
     * 刷新线程，开始播放时开启，暂停是取消
     */
    private class RefreshRunnable implements Runnable {

        @Override
        public void run() {
            int current = PAudio.getInstance().getCurrentPosition();
            progressBar.setProgress(current);

            int min = current / 1000 / 60;
            int sec = current / 1000 % 60;
            String progressStr = ""+min+"'"+sec+"\"/"+melody.getDurationString();

            Message msg = Message.obtain();
            msg.what = WHAT_UPDATE_PROGRESS_PLAY;
            msg.obj = progressStr;
            handler.sendMessage(msg);
        }
    }

    /**
     * 播放完成的回调
     */
    private class OnPlayCompleteListener implements PAlbum.IPlayComplete {

        @Override
        public void onCompletion() {
            if (playControlView != null) {
                playControlView.setStatus(PControlView.Status.PLAY);
            }

            if (refreshTask != null) {
                refreshTask.cancel(true);
            }

            albumView.stopRoll();
        }
    }

    /**
     * 更新UI
     */
    private class AlbumHandle extends Handler {


        @Override
        public void handleMessage(Message msg) {
            if (msg.what == WHAT_UPDATE_PROGRESS_PLAY) {
                //内部更新播放进度
                progressLabel.setText(msg.obj.toString());
                return;
            }

            if (msg.what == WHAT_LIKE) {
                //喜欢成功
                PUtil.toast(PAlbumActivity.this, "喜欢+1");
                melody.setLike(melody.getLike()+1);
                likeNum.setText(Long.toString(melody.getLike()) + $s(R.string.album_like_num));
                return;
            }

            JSONObject json = (JSONObject) msg.obj;
            try {
                JSONArray array = json.getJSONArray(PCommentService.KEY_COMMENTS);
                for (int i = 0; i < array.length(); i++) {
                    PComment comment = new PComment();
                    comment.fromJson(array.getJSONObject(i));
                    comments.add(comment);
                }

                for (int i = 0; i < 3 && i < comments.size(); i++) {
                    albumContainer.addView(commentAdapter.getView(i, null, albumContainer));
                }
            } catch (JSONException e) {
                Log.e(LOG_TAG, json.toString());
            }
        }
    }

    /**
     * 处理返回的json
     */
    private class HandleResult implements IHandleJson {

        @Override
        public void handleJson(JSONObject json) {
            try {
                //请求的是评论
                if (json.has(PCommentService.KEY_COMMENTS)) {
                    Message msg = Message.obtain();
                    msg.obj = json;
                    handler.sendMessage(msg);
                    return;
                }

                if (json.has(PApp.KEY_PROCESS)) {
                    long range = json.getLong(PApp.KEY_PROCESS_RANGE);
                    long at = json.getLong(PApp.KEY_PROCESS_AT);
                    progressBar.setMax((int) range);
                    progressBar.setSecondaryProgress((int) at);
                } else if (json.has(PApp.ERR_CODE)) {
                    int code = json.getInt(PApp.ERR_CODE);
                    if (code != PApp.ERR_SUCCESS) return;

                    album.play();
                }
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage());
            }
        }
    }

    //like the album
    private class OnLikeListener implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            album.likeMelody(melody, new IHandleJson() {
                @Override
                public void handleJson(JSONObject json) {
                int code = json.optInt(PError.KEY_CODE, PError.ERR_UNKNOWN);
                if (code == PError.ERR_SUCCESS) {
                    Message msg = Message.obtain();
                    msg.what = WHAT_LIKE;
                    handler.sendMessage(msg);
                } else if (code == PError.ERR_REPEAT) {
                    PUtil.toast(PApp.getAppContext(), "你已经喜欢过了");
                }
                }
            });
        }
    }

    //click the user
    private class OnUserListener implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setClass(PAlbumActivity.this, PUserActivity.class);
            intent.putExtra(PUser.KEY, melody.getUser());
            startActivity(intent);
        }
    }

    //click the comment
    private class OnCommentListener implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setClass(PAlbumActivity.this, PCommentActivity.class);
            intent.putExtra(PMelody.KEY, melody);
            startActivity(intent);
        }
    }

    //click the play control
    private class OnPlayListener implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            if (view instanceof PControlView) {
                PControlView controlView = (PControlView) view;
                switch (controlView.getStatus()) {
                    case PLAY:
                        play(controlView);
                        break;
                    case PAUSE:
                        pause(controlView);
                        break;
                    default:break;
                }
            }
        }
    }
}
